package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class MainActivity2 extends AppCompatActivity implements Runnable {
    private static final String TAG = "Main2";
    private float dollarRate;
    private float euroRate;
    private float wonRate;
    Handler handler;
    TextView result;
    Handler handler1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        result = findViewById(R.id.hi);

        Intent intent2 = getIntent();
        dollarRate = intent2.getFloatExtra("dollar_key", 0.15f);
        euroRate = intent2.getFloatExtra("euro_key", 0.14f);
        wonRate = intent2.getFloatExtra("won_key", 191.39f);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.1f);
        euroRate = sharedPreferences.getFloat("euro_date", 0.2f);
        wonRate = sharedPreferences.getFloat("won_rate", 123.0f);


        Log.i(TAG, "onCreate:dollar2=" + dollarRate);
        Log.i(TAG, "onCreate:euro2=" + euroRate);
        Log.i(TAG, "onCreate:won2=" + wonRate);

        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //    }
        //}).start();
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 7) {
                    Bundle bd1 = (Bundle) msg.obj;
                    dollarRate=bd1.getFloat("dollar-rate");
                    euroRate=bd1.getFloat("euro-rate");
                    wonRate=bd1.getFloat("won-rate");
                    Log.i(TAG, "handleMessage: dollar="+dollarRate);
                    Log.i(TAG, "handleMessage: euro="+euroRate);
                    Log.i(TAG, "handleMessage: won="+wonRate);
//                    String str = (String) msg.obj;
//                    Log.i(TAG, "handleMessage: str=" + str);
                    result.setText("updated");
                }
                super.handleMessage(msg);
            }
        };

        Thread t = new Thread(this);
        t.start();

    }

    public void click(View btn) {
        Log.i(TAG, "click:11");
        EditText input = findViewById(R.id.rmb);
        String s = input.getText().toString();
        if (s.length() == 0) {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i(TAG, "click:22");
        float inp = Float.parseFloat(s);
        float r = 0.0f;
        if (btn.getId() == R.id.btn_dollar) {
            r = inp * dollarRate;
        } else if (btn.getId() == R.id.btn_euro) {
            r = inp * euroRate;
        } else {
            r = inp * wonRate;
        }
        //TextView result=findViewById(R.id.result);

        result.setText(String.valueOf(r));

    }

    public void open(View btn) {
        Log.i(TAG, "open:33");
        openConfig();
    }

    private void openConfig() {
        Intent intent = new Intent(this, ConfigActivity.class);
        intent.putExtra("dollar_key", dollarRate);
        intent.putExtra("euro_key", euroRate);
        intent.putExtra("won_key", wonRate);

        Log.i(TAG, "open:dollar" + dollarRate);
        Log.i(TAG, "open:euro" + euroRate);
        Log.i(TAG, "open:won" + wonRate);

        //    startActivity(intent);
        startActivityForResult(intent, 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 3 && resultCode == 6) {
            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("dollar2");
            euroRate = bundle.getFloat("euro2");
            wonRate = bundle.getFloat("won2");
            Log.i(TAG, "onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult: euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonRate);

            SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate", dollarRate);
            editor.putFloat("euro_rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.apply();
            Log.i(TAG, "onActivityResult: save to sp");

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_settings) {
            openConfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.i(TAG, "run: run.....");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        URL url = null;
//        try {
//            url = new URL("https://www.usd-cny.com/bankofchina.htm");
//            HttpURLConnection http = (HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//
//            String html = inputStream2String(in);
//            Log.i(TAG, "run: html" + html);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
            Bundle bd1= new Bundle();
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG, "run: title="+ doc.title());
            Element table = doc.getElementsByTag("table").first();
//            //Log.i(TAG, "run: table"+table);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);
            for (Element tr: trs){
            Elements tds = tr.getElementsByTag("td");
            if (tds.size()>0){
                Element td1 = tds.first();
                Element td2 = tds.last();

                String str1 = td1.text();
                String str2 = td2.text();
                Log.i(TAG, "run: "+td1.text()+"-->"+td2.text());
                if ("欧元".equals(str1)){
                    bd1.putFloat("euro-rate",100f/Float.parseFloat(str2));
                }else if ("美元".equals(str1)){
                    bd1.putFloat("dollar-rate",100f/Float.parseFloat(str2));
                }if ("韩元".equals(str1)){
                    bd1.putFloat("won-rate",100f/Float.parseFloat(str2));
                }
            }
            }
//            Element td1 = table.selectFirst("tr:nth-child(27) > td.bz > a");
//            Log.i(TAG, "run: td1"+td1.text());

        } catch (IOException e) {
            e.printStackTrace();
        }


        Message msg = handler.obtainMessage(7, bd1);
        //    msg.what = 7;
        //    msg.obj = "hello from msg";
        handler.sendMessage(msg);
        Log.i(TAG, "run: sendMessage");
    }

    private String inputStream2String(InputStream inputStream)
            throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");
        while (true){
            int rsz = in.read(buffer,0, buffer.length);
            if(rsz < 0)
                break;
                out.append(buffer, 0, rsz);
            }
            return out.toString();
        }
    }
